package com.pdf.controller;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.pdf.PDFParser;
import org.apache.tika.sax.BodyContentHandler;
import org.aspectj.util.FileUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/")
public class PdfResolveController {

//	@Value("#{systemProperties['user.dir']}")
	private String localPicPath = "D:\\ocr";


	/**
	 * pdf解析和转图片
	 * @param files
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/fileUpload1")
	@ResponseBody
	public  List<Map<String, List<String>>> fileUploadByPDFBox1(@RequestParam("files") MultipartFile[] files) throws Exception {
		List<Map<String, List<String>>> results = new ArrayList<>();
		List<String> extractedTexts = new ArrayList<>();
		for (MultipartFile file:files) {
			InputStream inputStream = file.getInputStream();
			byte[] bytes = FileUtil.readAsByteArray(inputStream);
			inputStream = new ByteArrayInputStream(bytes);
			PDDocument doc = PDDocument.load(inputStream);
			int pageCount = doc.getNumberOfPages();
			PDFRenderer renderer = new PDFRenderer(doc);
			//todo 将 pdf 转换成 图片png
			// 保存图片路径（可选）
			List<String> imagePaths = new ArrayList<>();
			for (int i = 0; i < pageCount; i++) {
				String singleUuid = UUID.randomUUID().toString().replace("-", "");
				String singleLocalPath = localPicPath + "/" + singleUuid + ".png";
				BufferedImage bufferedImage = renderer.renderImageWithDPI(i, 120, ImageType.RGB);
				if (bufferedImage.getHeight() > 3000 || bufferedImage.getWidth() > 3000) {
					bufferedImage = renderer.renderImageWithDPI(i, 30, ImageType.RGB);
				}
				ImageIO.write(bufferedImage, "png", new File(singleLocalPath));
				imagePaths.add(singleLocalPath);
			}

			//todo 识别 pdf 内容，缺点：pdf 所有内容识别成字符串，以空格和换行分割，没有格式，二次处理有困难
			PDFTextStripper stripper = new PDFTextStripper();
			String text = stripper.getText(doc);
			extractedTexts.add(text);

			List<String> examData = extractPdfMetadata(doc);

			// 组装结果
			Map<String, List<String>> result = new HashMap<>();
			result.put("metadata", examData);  // 字段化数据
			result.put("imagePaths", imagePaths);  // 图片路径
			results.add(result);


			doc.close();
			inputStream.close();

		}
		return results;
	}


	/**
	 * pdf解析
	 * @param files
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/fileUpload2")
	@ResponseBody
	public  List<Map<String, List<String>>> fileUploadByPDFBox2(@RequestParam("files") MultipartFile[] files) throws Exception {
			List<Map<String, List<String>>> results = new ArrayList<>();
			List<String> extractedTexts = new ArrayList<>();
			for (MultipartFile file:files) {
			InputStream inputStream = file.getInputStream();
			byte[] bytes = FileUtil.readAsByteArray(inputStream);
			inputStream = new ByteArrayInputStream(bytes);
			PDDocument doc = PDDocument.load(inputStream);
			int pageCount = doc.getNumberOfPages();
			PDFRenderer renderer = new PDFRenderer(doc);
			//todo 将 pdf 转换成 图片png
			// 保存图片路径（可选）
			List<String> imagePaths = new ArrayList<>();
		    for (int i = 0; i < pageCount; i++) {
				String singleUuid = UUID.randomUUID().toString().replace("-", "");
				String singleLocalPath = localPicPath + "/" + singleUuid + ".png";
				BufferedImage bufferedImage = renderer.renderImageWithDPI(i, 120, ImageType.RGB);
				if (bufferedImage.getHeight() > 3000 || bufferedImage.getWidth() > 3000) {
					bufferedImage = renderer.renderImageWithDPI(i, 30, ImageType.RGB);
				}
				ImageIO.write(bufferedImage, "png", new File(singleLocalPath));
				imagePaths.add(singleLocalPath);
			}

			//todo 识别 pdf 内容，缺点：pdf 所有内容识别成字符串，以空格和换行分割，没有格式，二次处理有困难
			PDFTextStripper stripper = new PDFTextStripper();
			String text = stripper.getText(doc);
			extractedTexts.add(text);

			List<String> examData = extractPdfMetadata(doc);

			// 组装结果
			Map<String, List<String>> result = new HashMap<>();
			result.put("metadata", examData);  // 字段化数据
			result.put("imagePaths", imagePaths);  // 图片路径
			results.add(result);


			doc.close();
			inputStream.close();

		}
		return results;
	}

	/**
	 * 将 PDF 内容解析为字段名-字段值的 Map
	 *
	 * @param text PDF 提取的原始文本
	 * @return 结构化字段 Map
	 */
	private List<String> extractPdfMetadata(PDDocument doc) throws Exception {
		Map<String, String> metadataMap = new HashMap<>();

		// 使用正则表达式匹配 "key: value" 格式的内容
		PDFTextStripper stripper = new PDFTextStripper();
		String text = stripper.getText(doc);

		// 按行分割文本
		String[] lines = text.split("\\r?\\n");

		// 定义正则表达式：用于匹配 "字段名: 字段值"
		Pattern pattern = Pattern.compile("([^:]+):\\s*(.*)");
		List<String> linList = new ArrayList<>();
		for (String line : lines) {
//			Matcher matcher = pattern.matcher(line.trim());
//			if (matcher.matches()) {
//				String key = matcher.group(1).trim();  // 提取字段名
//				String value = matcher.group(2).trim();  // 提取字段值
//				metadataMap.put(key, value);
//			}
			linList.add(line);
		}
//		metadataMap.put("linMsg", linList);
		return linList;
//		return metadataMap;
	}
//	private Map<String, String> parseExamDataToMap(String text) {
//		Map<String, String> examData = new HashMap<>();
//
//		// 定义正则表达式模式
//		Pattern examNamePattern = Pattern.compile("考试名称:\\s*(.*?)\\s*姓名:");
//		Pattern namePattern = Pattern.compile("姓名:\\s*(.*?)\\s*成绩:");
//		Pattern scorePattern = Pattern.compile("成绩:\\s*(.*?)\\s*及格:");
//		Pattern passPattern = Pattern.compile("及格:\\s*(.*?)\\s*");
//
//		Matcher examNameMatcher = examNamePattern.matcher(text);
//		Matcher nameMatcher = namePattern.matcher(text);
//		Matcher scoreMatcher = scorePattern.matcher(text);
//		Matcher passMatcher = passPattern.matcher(text);
//
//		if (examNameMatcher.find()) {
//			examData.put("考试名称", examNameMatcher.group(1).trim());
//		}
//		if (nameMatcher.find()) {
//			examData.put("姓名", nameMatcher.group(1).trim());
//		}
//		if (scoreMatcher.find()) {
//			examData.put("成绩", scoreMatcher.group(1).trim());
//		}
//		if (passMatcher.find()) {
//			examData.put("及格", passMatcher.group(1).trim());
//		}
//
//		return examData;
//	}

	@RequestMapping("/fileUpload3")
	@ResponseBody
	public void fileUploadByTikaPDF3(@RequestParam("files") MultipartFile[] files) throws Exception{
		for (MultipartFile file:files) {
			tikaPDFExtractor(file.getInputStream());
		}
	}

	public void tikaPDFExtractor(InputStream inputStream){
		try {
			// 创建解析上下文
			ParseContext context = new ParseContext();
			// 创建 PDF 解析器
			PDFParser parser = new PDFParser();
			// 创建内容处理器，用于存储提取的文本
			BodyContentHandler handler = new BodyContentHandler();
			// 读取 PDF 文件
			Metadata metadata = new Metadata();
			// 解析 PDF 文件
			parser.parse(inputStream, handler, metadata, context);
			// 打印提取的文本
			System.out.println(handler.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}



}
